package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 项目Token相关统一管理接口* @author: LJT*
 *
 */

public class apiFaxDownload implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiFaxDownload.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String result = "";

        String faxid = KHUtil.FastJsonNull(request.getParameter("faxid"));
        log.debug("原始Get请求参数:" + faxid);

        try {
            // 获取token
            JSONObject getTokenJson = JSONObject.fromObject(Util.doHttpGet(KHDBConfig.getAPIURL(eliteBean, "Local_Token"), "UTF-8", 12000, 0));
            String access_token = getTokenJson.getJSONObject("data").getString("access_token");
            log.debug("获取调用Token:" + access_token);

            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/x-www-form-urlencoded");

            Map<String, String> callParams = new HashMap<String, String>();
            callParams.put("token", access_token);
            callParams.put("faxid", faxid);
            callParams.put("type", "pdf");

            String callBody = KHUtil.urlencode(callParams, "");

            HttpPost httppost = new HttpPost(KHDBConfig.getAPIURL(eliteBean, "FAX-downloadURL"));
            if (headParams != null) {
                Iterator entries = headParams.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    String key = (String) entry.getKey();
                    log.debug("key:" + key);
                    String value = (String) entry.getValue();
                    log.debug("value:" + value);
                    httppost.addHeader(key, value);
                }
            }

            CloseableHttpClient httpClient = HttpClients.createDefault();

            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();//设置请求和传输超时间
            httppost.setConfig(requestConfig);

            StringEntity se = new StringEntity(callBody, "UTF-8");
            httppost.setEntity(se);
            HttpResponse httpResponse = httpClient.execute(httppost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                byte[] data = EntityUtils.toByteArray(httpEntity);

                //存入磁盘
                String saveFile = faxid + "-" + KHUtil.getRandomString(6) + ".pdf";
                FileOutputStream fos = new FileOutputStream(saveFile);
                fos.write(data);
                fos.close();
                fos.flush();

                log.info("文件下载成功！开始上传NGS...");

                result = uploadNGS(eliteBean, saveFile);

                log.debug("上传NGS完成：【" + result + "】");

            }

            httpClient.close();

            response.sendRedirect(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-Get") + result);

        } catch (Exception e) {
            log.error("接口处理异常", e);

        }

        return "";
    }


    public static String uploadNGS(EliteBean eliteBean, String srcFileName) {

        String ngsFSToken = Util.getAuthToken(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-authUrl"), "elite.ngs", "Letmein_0308");
        log.debug("获取NGS上次Token：" + ngsFSToken);

        File tempFile = new File(srcFileName.trim());
        String fileName = tempFile.getName();

        String uploadResult = Util.uploadFile(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-upload_url"), srcFileName, "/wopdf", KHUtil.getNameWithoutSuffix(fileName), "", ngsFSToken);
        log.debug("文件上传NGS结果：" + uploadResult);

        JSONObject resultJson = JSONObject.fromObject(uploadResult);

        String code = resultJson.getString("code");
        if (code.equals("1")) {
            return resultJson.getString("value");
        } else {
            return null;
        }
    }

}
